package com.fuze.navi.controller;

import com.fuze.navi.common.Advice;
import com.fuze.navi.common.Constant;
import com.fuze.navi.common.NaviException;
import com.fuze.navi.common.Result;
import com.fuze.navi.domain.dto.UserDTO;
import com.fuze.navi.domain.vo.ResetPwdVO;
import com.fuze.navi.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

/**
 * @author sepc_
 * @date 3/16/2021 15:17
 * 用户模块相关接口
 */
@RequiredArgsConstructor
@Slf4j
@RestController
public class UserController {

    final UserService userService;

    final StringRedisTemplate stringRedisTemplate;

    /**
     * 用户注册接口
     */
    @PostMapping("/user/register")
    public Result register(@Validated @RequestBody UserDTO userDTO) {
        userService.register(userDTO);
        return Result.ok();
    }

    /**
     * 登录接口
     */
    @PostMapping("/user/login")
    public Result login(@RequestBody @Validated UserDTO user) {
        log.info("user = {}", user);
        Optional<String> optional = userService.checkAccount(user);
        return optional.map(Result::ok).orElseGet(() -> Result.err(Advice.FAILED_GENERATION_TOKEN));

    }

    /**
     * 重置用户密码
     */
    @PutMapping("/user/resetPwd")
    public Result resetPwd(@Validated @RequestBody ResetPwdVO resetPwdVO, HttpServletRequest request) {
        String newPwd = resetPwdVO.getNewPwd().trim();
        String confirmPwd = resetPwdVO.getConfirmPwd().trim();
        if (!newPwd.equals(confirmPwd)) {
            throw new NaviException(Advice.INCONSISTENT_PASSWORDS);
        }
        String token = request.getHeader(Constant.AUTH_TOKEN);
        String tokenVal = stringRedisTemplate.opsForValue().get(token);
        assert tokenVal != null;
        String[] tokenValSplit = tokenVal.split(Constant.DELIMITER);
        userService.resetPwd(tokenValSplit[0], newPwd);
        stringRedisTemplate.delete(token);
        return Result.ok();
    }

}
